import QuadTreeNode from "./QuadTreeNode";
import Misc from "./Misc";
import EventUtil from "./event/EventUtil";
import { Events } from "./event/Event";

const { ccclass, property } = cc._decorator;
@ccclass

export default class AABB extends cc.Component {

  public static GetComponent(node: cc.Node) {
    return node.getComponent(AABB);
  }

  public static index = 0;
  private static T: number = 5;
  private static PI: number = 3.1415926 / 180;

  @property(cc.Label)
  private labIndex: cc.Label = null;

  private mArrQuadNodeRecord: QuadTreeNode[] = [];

  private mBoundingBox: cc.Rect = new cc.Rect();

  // 测试使用
  private mNumTime: number = 0; // AABB.T;
  private mNumAddX: number = 0;
  private mNumAddY: number = 0;
  public mNumIndex: number = null;

  protected onLoad() {

    const angle = Misc.getRandomInt(0, 360) * AABB.PI;
    this.mNumAddX = Math.cos(angle);
    this.mNumAddY = Math.sin(angle);
    this.node.x = Misc.getRandomInt(-640, 640);
    this.node.y = Misc.getRandomInt(-360, 360);
    this.mBoundingBox = this.node.getBoundingBox();

    this.mNumIndex = AABB.index ++;
    this.labIndex.string = "" + this.mNumIndex;

    EventUtil.Dispatcher.on(Events.EVENT_DELETE_AABB + this.mNumIndex, this.onRemoveSelf, this);
  }

  public onUpdate(dt: number) {
  // public update(dt: number) {
    this.mNumTime += dt;
    if (this.mNumTime > AABB.T) {
      this.mNumTime = 0;
      const angle = Misc.getRandomInt(0, 360) * AABB.PI;
      this.mNumAddX = Math.cos(angle);
      this.mNumAddY = Math.sin(angle);
      // this.mNumAddX = 0;
      // this.mNumAddY = 0;
    }

    this.node.x += this.mNumAddX;
    this.node.y += this.mNumAddY;

    if (this.node.x >= 600  || this.node.x <= -600) {
      this.mNumAddX *= -1;
    }

    if (this.node.y >= 350 || this.node.y <= -350) {
      this.mNumAddY *= -1;
    }

    this.clearQuadnodeRecord();
    EventUtil.Dispatcher.emit(Events.EVENT_RESET_AABB_PATH, this);
  }

  public get BoundingBox(): cc.Rect {
    this.mBoundingBox.x = this.node.x - this.mBoundingBox.width / 2;
    this.mBoundingBox.y = this.node.y - this.mBoundingBox.height / 2;
    return this.mBoundingBox;
  }

  // 增加节点记录
  public addQuadnodeRecord(node: QuadTreeNode) {
    const index = this.mArrQuadNodeRecord.indexOf(node);
    if (index === -1) {
      this.mArrQuadNodeRecord.push(node);
    }
  }

  // 删除节点记录
  public delQuadnodeRecord(node: QuadTreeNode) {
    const index = this.mArrQuadNodeRecord.indexOf(node);
    if (index !== -1) {
      Misc.fastRemoveAt(this.mArrQuadNodeRecord, index);
    }
  }

  // 清除记录
  public clearQuadnodeRecord() {
    for (let i = 0, len = this.mArrQuadNodeRecord.length; i < len; i++) {
      this.mArrQuadNodeRecord[i].delObject(this, false);
    }
    this.mArrQuadNodeRecord = [];
  }

  // 删除自身
  private onRemoveSelf() {
    this.clearQuadnodeRecord();
    this.node.destroy();
  }
}
